package com.henz4help.app.common;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class HttpWorker {
	
	
	public HttpResponse getJsonResponse(String url, Map<String, Object> params) throws Exception{
		HttpResponse returnValue = null;
		
		int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
		HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
		HttpClient client = new DefaultHttpClient(httpParams);

		HttpPost request = null;
		StringEntity entity = null;
		
        JSONObject json = new JSONObject();
        Set<String> keyIt = params.keySet();

		
		for( String key: keyIt){
			json.put(key, params.get(key));
		}
		Util.Log("request Json StringEntity Start----------------------------------------");
		//Util.Log(json.toString());
		for( String key: keyIt){
			json.put(key, params.get(key));
			Util.Log("[" + key + "][" + params.get(key) + "]");
		}
		Util.Log("request Json StringEntity End----------------------------------------");
		
		request = new HttpPost(url);
		
		entity = new StringEntity(json.toString());
        //entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");
		
		request.setEntity(entity);
		
		returnValue = client.execute(request);
			
		
		return returnValue;
	}
	
	public JSONObject requestSingleJson(String url, Map<String, Object> params) {
		JSONObject returnValue = null;

		HttpResponse response = null;
		HttpEntity hEntity = null;
		
		try {
			
			response = getJsonResponse( url, params );
			
			Util.Log("request Json StringEntity----------------------------------------");
			/*
            Util.Log(response.getStatusLine().getReasonPhrase());
            Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
            	Util.Log(headers[i].getName() + " : " + headers[i].getValue());
            }
            */
            hEntity = response.getEntity();
            
            Util.Log("request Json StringEntity----------------------------------------");
            
            returnValue = new JSONObject(EntityUtils.toString(hEntity));
            
            //Util.Log("hEntity[" + hEntity + "]");
            Util.Log("hEntity[" + returnValue + "]");
            
            
		} catch (Exception e) {
			//returnValue = e.toString();
			Util.Log("requestJson Exception----------------------------------------");
			Util.Log(String.valueOf(returnValue));
			Util.Log("requestJson Exception----------------------------------------");
		}
		
		return returnValue;
	}
	
	public String requestJson(String url, Map<String, Object> params) {
		String returnValue = null;
		
		int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
		HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
		HttpResponse response = null;
		HttpEntity hEntity = null;
		
		try {

			response = getJsonResponse( url, params );
            
            /*
			ByteArrayEntity ent =
            		new ByteArrayEntity(json.toString().getBytes("UTF8"));
            ent.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");
            
            request.setEntity(ent);

            client = new DefaultHttpClient();
            response = client.execute(request);
            hEntity = response.getEntity();
            */
			Util.Log("request Json StringEntity----------------------------------------");
			
            Util.Log(response.getStatusLine().getReasonPhrase());
            Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
            	Util.Log(headers[i].getName() + " : " + headers[i].getValue());
            }
            
            Util.Log("hEntity[" + hEntity + "]");
            Util.Log("hEntity[" + EntityUtils.toString(hEntity) + "]");
            
            Util.Log("request Json StringEntity----------------------------------------");
            
            returnValue = EntityUtils.toString(hEntity);
            
		} catch (Exception e) {
			Util.Log("requestJson Exception----------------------------------------");
			Util.Log(e.toString());
			Util.Log("requestJson Exception----------------------------------------");
		}
		
		return returnValue;
	}
	
	
	public String request(String url, Map<String, String> params) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost req = new HttpPost(url);

            Util.Log("executing request to " + url);
            
            List<NameValuePair> nvps = null;
            
            
            
            
			if((params != null) && (params.size() > 0)) {
				nvps = new ArrayList<NameValuePair>();
				for(String key : params.keySet()) {
					nvps.add(new BasicNameValuePair(key, params.get(key)));
					//nvps.add(new Basinc)
				}
			}
			
			if(nvps != null) {
				try {
					req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
				} catch (UnsupportedEncodingException e) {
				}
			}

            HttpResponse rsp = httpclient.execute(req);
            HttpEntity entity = rsp.getEntity();

            Util.Log("----------------------------------------");
            Util.Log(rsp.getStatusLine().getReasonPhrase());
            Header[] headers = rsp.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
            	Util.Log(headers[i].getName() + " : " + headers[i].getValue());
            }
            Util.Log("----------------------------------------");
            
            return EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
        	Util.Log(e.toString());
			return null;
		} catch (IOException e) {
			Util.Log(e.toString());
			return null;
		} finally {
           httpclient.getConnectionManager().shutdown();
        }
	}
}
